﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text;
using System.Text.RegularExpressions;

namespace PK2
{
    internal static class Helper
    {
        internal static Tuple<bool,SnapshotSpan> IsInComment(ITextView m_textView, IClassifierAggregatorService aggregatorService)
        {

            if (m_textView.Caret.Position.BufferPosition == 0) return new Tuple<bool, SnapshotSpan>(false, new SnapshotSpan());

            SnapshotPoint currentPoint = (m_textView.Caret.Position.BufferPosition) -1;

            var res = aggregatorService.GetClassifier(m_textView.TextBuffer);
            var classificationSpans = res.GetClassificationSpans(currentPoint.GetContainingLine().Extent);
            
            //Check if we are writting in a comment
            var currentSpan = (from cspan in classificationSpans
                         let name = cspan.ClassificationType.Classification.ToLower()
                         where name.Contains("comment") && cspan.Span.Contains(currentPoint)
                         select cspan).FirstOrDefault();

            return new Tuple<bool, SnapshotSpan>(currentSpan != null, (currentSpan == null ? new SnapshotSpan(): currentSpan.Span));
        }

        internal static ParsedLine SplitLine(SnapshotSpan span)
        {
            var regex = new Regex(@"^.*" + Regex.Escape(PKTokenConstants.InitToken.ToString()) + 
                                  @"(?<token>\w+)(" + Regex.Escape(PKTokenConstants.CommandToken.ToString()) + 
                                  @"(?<command>\w+))?(" + Regex.Escape(PKTokenConstants.ArgumentToken.ToString()) + "(?<args>.*))?");
            var matchs = regex.Match(span.GetText());

            var res = new ParsedLine();
            if (!matchs.Success)
                throw new Exception("Invalid input :S");

            res.Token = matchs.Groups["token"].Value;
            res.Command = matchs.Groups["command"].Value;
            res.Arguments = matchs.Groups["args"].Value;

            return res;
        }
                         
    }
}
